package com.hjw.service.impl;

import com.hjw.dao.BookDao;
import com.hjw.entity.Book;
import com.hjw.entity.Type;
import com.hjw.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * <p>Project:Academic - BookServiceImpl<p>
 *
 * @author IvanWei玮 -- maste
 * @version 1.0
 * @DataTime 2025/4/12 23:11
 * @since 1.8
 */
@Primary
@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookDao bookDao;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private RedisTemplate<String, Type> rtType;

    @Override
    public List<Book> findAll(){
        String s = redisTemplate.opsForValue().get("book", 0, -1);
        return bookDao.findAll();
    }

    @Override
    public Book findById(int id){

        Object book = redisTemplate.opsForHash().get("book", id);

        Book redisBook = (Book) book;

        if (redisBook != null) {
            return redisBook;
        }

        Book sqlBook = bookDao.findById(id);
        redisTemplate.opsForHash().put("book", id, sqlBook);
        return bookDao.findById(id);
    }

    @Override
    public List<Book> findTop(int num) {
        return bookDao.findTop(num);
    }

    @Override
    public List<Book> findByPage(Map<String, Object> map) {
        return bookDao.findByPage(map);
    }

    @Override
    public List<Book> findByPageKey(Map<String, Object> map) {
        return bookDao.findByPageKey(map);
    }

    @Override
    public int count(Map<String, Object> map) {
        return bookDao.count(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.NESTED)
    public int update(Map<String, Object> map) {
        redisTemplate.delete("book:"+map.get("id"));
        int update = bookDao.update(map);
        redisTemplate.delete("book:"+map.get("id"));
        return update;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.NESTED)
    public int add(Map<String, Object> book) {
        return bookDao.add(book);
    }

}
